package com.example.su_shi_tan_sig_in.child

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.example.library_common.utils.normalShortToast
import com.example.su_shi_tan_bas_lib.base.BaseDataBindingFragment
import com.example.su_shi_tan_bas_lib.constant.CLICK_BLE
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.OnTextListener
import com.example.su_shi_tan_bas_lib.utils.timer.BaseTimerTask
import com.example.su_shi_tan_bas_lib.utils.timer.ITimerListener
import com.example.su_shi_tan_core.constant.REGEX_EMAIL
import com.example.su_shi_tan_core.constant.REGEX_PASSWORD_NUMBER_AND_LETTER
import com.example.su_shi_tan_sig_in.R
import com.example.su_shi_tan_sig_in.databinding.RegisterFragmentBinding
import java.util.*
import java.util.regex.Pattern

class RegisterFragment(loginProxy: LoginProxy) : BaseDataBindingFragment<RegisterFragmentBinding>(),
    LoginProxy by loginProxy,
    View.OnClickListener, OnTextListener, ITimerListener {

    companion object {
        fun newInstance(loginProxy: LoginProxy): RegisterFragment {
            val args = Bundle()
            val fragment = RegisterFragment(loginProxy)
            fragment.arguments = args
            return fragment
        }
    }

    //手机
    private var signUpPhone = ""

    //登录密码
    private var signUpPassWord = ""

    //支付密码
    private var signUpPayingPassWord = ""

    //  邀请码 （测试8个8）
    private var signUpInvitedCoding = ""

    //邮箱
    private var signUpEmail = ""

    //验证码
    private var signUpVerifyCoding = ""

    private var mTimerTask: BaseTimerTask? = null

    private var mTimer: Timer? = null

    private var timer = 60

    private val handler: Handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
    }

    override fun layoutId(): Int {
        return R.layout.register_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.setBackgroundColor(Color.TRANSPARENT)

        viewBinder.onViewClick = this
        viewBinder.onTextListener = this

        viewBinder.signUpEMail.addExMethod({ validatorForEMail() })

        viewBinder.signUpPassWord.addExMethod({
            validatorPassWordSameCode()
            validatorPassWordNumbersAndLetter()
        })

        viewBinder.signUpPayingPassWord.addExMethod({
            validatorPayingPassWordNumbersAndLetter()
            validatorPayingPassWordSameCode()
        })
    }

    private fun validatorPayingPassWordSameCode() = passWordSameCode(signUpPayingPassWord)

    private fun validatorPayingPassWordNumbersAndLetter() =
        passWordNumbersAndLetter(signUpPayingPassWord)

    private fun validatorPassWordNumbersAndLetter() = passWordNumbersAndLetter(signUpPassWord)

    private fun validatorPassWordSameCode() = passWordSameCode(signUpPassWord)


    //验证密码是否为数字与字母组合
    private fun passWordNumbersAndLetter(test: String): String {
        var res = ""
        if (test.isEmpty()) return res

        val p = Pattern.compile(REGEX_PASSWORD_NUMBER_AND_LETTER)

        val matcher = p.matcher(test)

        if (!matcher.matches()) {
            res = _mActivity.getString(R.string.password_by_num_and_letter)
        }
        return res
    }

    //验证密码不能为同一数字
    private fun passWordSameCode(test: String): String {
        var res = ""

        if (test.isEmpty()) return res

        val toCharArray = test.toCharArray()

        var sameCount = 0

        val firstChar = toCharArray[0]

        toCharArray.forEach {

            if (firstChar == it) {

                sameCount++

            }
        }
        if (sameCount == signUpPassWord.length) {

            res = _mActivity.getString(R.string.password_same_code_0)

        }
        return res
    }


    //验证邮箱格式
    private fun validatorForEMail(): String {
        var res = ""

        if (signUpEmail.isEmpty()) return res

        val p = Pattern.compile(REGEX_EMAIL)
        val matcher = p.matcher(signUpEmail)

        if (!matcher.matches()) {
            res = _mActivity.getString(R.string.email_not_validate)
        }
        return res
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.sign_up_tv -> {
                if (!checkInfo()) return

                if (!CLICK_BLE) return

                CLICK_BLE = false

                registerAccount()
            }
            R.id.sign_in_now -> {
                //立即登录
                intoSignIn()
            }
            R.id.require_verify_coding -> {
                RestClient.builder()
                    .url(R.string.register_verify)
                    .raw(
                        JSON.toJSONString(
                            mapOf(
                                "phone" to signUpPhone,
                                "type" to "register"
                            )
                        )
                    )
                    .success {
                        startTimer()
                    }.failure {
                        normalShortToast(_mActivity, R.string.net_work_failed)
                    }
                    .error { _, msg ->
                        normalShortToast(_mActivity, msg)
                    }.build().post()
//
            }
        }
    }

    private fun registerAccount() {
        val maps = mapOf(

            "phone" to signUpPhone,

            "email" to signUpEmail,

            "password" to signUpPassWord,

            "pay_pwd" to signUpPayingPassWord,

            "invite_code" to signUpInvitedCoding,

            "captcha" to signUpVerifyCoding
        )
        RestClient.builder()
            .url(R.string.SignUp)
            .raw(JSON.toJSONString(maps))
            .success {
                CLICK_BLE = true
                parserSignUpData(it)
            }
            .error { _, msg ->
                CLICK_BLE = true
                onSignUpFailed(msg)
            }
            .failure {
                CLICK_BLE = true
                onSignUpFailed(_mActivity.getString(R.string.sign_up_failed_22))
            }

            .build()
            .post()
    }

    private fun onSignUpFailed(msg: String) {
        normalShortToast(_mActivity,msg)

    }

    private fun parserSignUpData(it: String?) {

        normalShortToast(_mActivity,"注册成功")

        intoSignIn()
    }

    private fun checkInfo(): Boolean {
        var flags = true

        val formViews = arrayOf(
            viewBinder.signUpPhone,
            viewBinder.signUpPassWord,
            viewBinder.signUpPayingPassWord,
            viewBinder.signUpInvitedCoding,
//            viewBinder.signUpEMail,
            viewBinder.signUpVerifyCoding
        )

        for (item in formViews) {

            val validator = item.validator()

            if (validator?.isNotEmpty() == true) {

                normalShortToast(_mActivity,validator)

                flags = false
                break
            }
        }
        return flags
    }

    private fun startTimer() {
        if (mTimerTask !== null) return


        mTimer = Timer()

        mTimerTask = BaseTimerTask(this)
        mTimer?.schedule(mTimerTask, 1000, 1000)
    }

    private fun stopTimer() {


        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }

        if (mTimerTask != null) {
            mTimerTask?.cancel()
            mTimerTask = null
        }

        viewBinder.requireVerifyCoding.setText(R.string.require_verify_coding)
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.sign_up_phone -> {
                //手机
                signUpPhone = s?.toString() ?: ""
            }
            R.id.sign_up_passWord -> {
                //登录密码
                signUpPassWord = s?.toString() ?: ""
            }
            R.id.sign_up_paying_passWord -> {
                //支付密码
                signUpPayingPassWord = s?.toString() ?: ""
            }
            R.id.sign_up_invited_coding -> {
                //邀请码
                signUpInvitedCoding = s?.toString() ?: ""
            }
            R.id.sign_up_e_mail -> {
                //邮箱
                signUpEmail = s?.toString() ?: ""
            }

            R.id.sign_up_verify_coding -> {
                //验证码
                signUpVerifyCoding = s?.toString() ?: ""
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopTimer()
    }

    @SuppressLint("SetTextI18n")
    override fun onTimer() {
        handler.post {

            timer--

            if (timer < 0) {
                stopTimer()
            } else {
                viewBinder.requireVerifyCoding.text = "${timer}秒后自动取消"
            }

        }
    }
}